package com.znufe.exam.third.votesdkController;

import com.alibaba.fastjson.JSONObject;
import com.znufe.exam.base.BaseConstant;
import com.znufe.exam.base.RestResponse;
import com.znufe.exam.base.SystemCode;
import com.znufe.exam.domain.ClassInteractionCustomerAnswer;
import com.znufe.exam.service.ClassInteractionCustomerAnswerService;
import com.znufe.exam.service.QuestionService;
import com.znufe.exam.third.votesdk.JConnectCallback;
import com.znufe.exam.third.votesdk.JVoteSdk;
import com.znufe.exam.third.votesdk.impl.JChoices;
import com.znufe.exam.third.votesdk.impl.JOnConnect;
import com.znufe.exam.third.votesdk.impl.JOnSignin;
import com.znufe.exam.viewmodel.admin.question.QuestionEditRequestVM;
import com.znufe.exam.viewmodel.vote.VoteVM;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @ProjectName:
 * @Package: com.znufe.exam.third.votesdkTest
 * @ClassName: VoteSdkController
 * @Author: bot
 * @Description:
 * @Date: 2020/6/14 14:31
 * @Version: 1.0
 */
@Api(value = "答题器对外接口" , tags = "答题器对外接口")
@RequestMapping(value = "/api/votesdk")
@RestController
public class VoteSdkController {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public RedisTemplate<String, Object> redisTemplate;
    @Autowired
    public QuestionService questionService;

    @Autowired
    public ClassInteractionCustomerAnswerService classInteractionCustomerAnswerService;



    @GetMapping("/conn")
    @ApiOperation(value = "答题器基站连接接口", notes = "建立答题器与基站连接服务，无参输入，成功返回 code=0, 否则返回601错误码")
    public RestResponse<String> getConnectSDK() {
        logger.info("答题器基站连接接口 conn is begin");
        try {
            JConnectCallback OnConnect = new JOnConnect();
            //连接基站
            JVoteSdk.INSTANCE.Connect((byte) 0x00, "", OnConnect);
            return RestResponse.ok();

        } catch (Exception e) {
            logger.error("连接答题器失败：" + e.getMessage());
            return RestResponse.fail(SystemCode.VoteSDKConnection.getCode(), e.getMessage());
        }
    }

    /**
     * @return
     */
    @GetMapping("/sign")
    @ApiOperation(value = "学生签到信息信息服务", notes = "学生答题器签到信息服务接口，无参接口，签到成功后会调用回调函数，" +
            "查询签到成功信息通过学生接口服务")
    public RestResponse<String> getJSignin() {
        logger.info("学生签到信息信息服务 getJSignin is begin");
        try {
            JOnSignin jSignin = new JOnSignin();
            //获取签到信息
            JVoteSdk.INSTANCE.Signin((short) BaseConstant.ALL_VOTE, (short) BaseConstant.ALL_VOTE, (byte) 0x00, jSignin);
            return RestResponse.ok();

        } catch (Exception e) {
            logger.error("获取签到信息失败：" + e.getMessage());
            return RestResponse.fail(SystemCode.VoteSDKConnection.getCode(), e.getMessage());
        }
    }

    /**
     * 答题器答案业务操作流程， 获取当前题目信息、答案个数、题目类型、必选项个数、是否允许修改等信息，
     * @return
     */
    @PostMapping("/choise")
    @ApiOperation(value = "答题器答案提交服务", notes = "答题器答案提交服务，需要传入当前试卷ID、题目ID、班级ID，其他可为空", produces = "application/json" )
    public RestResponse<String> getChoise(@RequestBody VoteVM voteVM) {
        logger.info("答题器答案提交服务 getChoise is begin, voteVM is:" + voteVM.toString());
        if (voteVM != null && voteVM.getQuestionEditRequestVM().getId() != 0 ) {

            if( voteVM.getExamType() == BaseConstant.EXAM_TYPE_INTERACT){
                //对于课堂互动类型的题目，其答题记录不做存储，每次调用该接口时，删除其相同问卷、相同问题的答题记录
                //TODO 删除课堂互动表中的数据
                ClassInteractionCustomerAnswer classInteractionCustomerAnswer = new ClassInteractionCustomerAnswer();
                classInteractionCustomerAnswer.setQuestionId(voteVM.getQuestionEditRequestVM().getId());
                //试卷ID复用classId字段
                classInteractionCustomerAnswer.setClassId(voteVM.getExamId());
                //置为删除
                classInteractionCustomerAnswer.setIsDeleted(BaseConstant.SUCCESS);
                classInteractionCustomerAnswerService.updateByPrimaryKeySelective(classInteractionCustomerAnswer);

            }

            try {
                //总选择项个数
                int selCount = 0;
                //必选项个数
                int mustSel = 0;
                //可选项个数
                int sel = 0;
                JChoices jChoices = new JChoices();
                QuestionEditRequestVM questionEditRequestVM = questionService.getQuestionEditRequestVM( voteVM.getQuestionEditRequestVM().getId());
                if(questionEditRequestVM != null){
                    //获取答案信息，回写以下方法
                    logger.info("questionEditRequestVM is:" + questionEditRequestVM.toString());
                    logger.info("questionEditRequestVM answer number is:" + questionEditRequestVM.getItems().size());
                    if(questionEditRequestVM.getQuestionType().equals(BaseConstant.TrueFalse)){
                        selCount = 2;
                        mustSel = 1;
                        sel = 1;
                    }else if(questionEditRequestVM.getQuestionType().equals(BaseConstant.SingleChoice)){
                        //Sel 同时不可超过SelCount，如果为1时表示单选，其他值表示多选。
                        selCount = questionEditRequestVM.getItems().size();
                        mustSel = 1;
                        sel = 1;
                    }else if(questionEditRequestVM.getQuestionType().equals(BaseConstant.MultipleChoice)){
                        selCount = questionEditRequestVM.getItems().size();
                        mustSel = 1;
                        sel = questionEditRequestVM.getItems().size();
                    }
                    voteVM.getQuestionEditRequestVM().setQuestionType(questionEditRequestVM.getQuestionType());
                    logger.info("questionEditRequestVM  selCount is:" + selCount + "; sel is :" + sel + "; musetSel is: " + mustSel);
                    //获取题目基本信息，将试题编号、班级信息、题目编号存放在临时表中
                    redisTemplate.opsForValue().set(BaseConstant.VOTE, voteVM);
                    //开始答题
                    JVoteSdk.INSTANCE.Choices((short) BaseConstant.ALL_VOTE, (short) BaseConstant.ALL_VOTE, (byte) selCount, (byte) sel, (byte) mustSel, (byte) 0x01, (byte) 0x01, (byte) 0x00, jChoices);
                    return RestResponse.ok();
                }else{
                    logger.error("获取题目信息失败");
                    return RestResponse.fail(SystemCode.NoDataExist.getCode(), SystemCode.NoDataExist.getMessage());
                }

            } catch (Exception e) {
                logger.error("获取选择题信息失败：" + e.getMessage());
                return RestResponse.fail(SystemCode.VoteSDKConnection.getCode(), e.getMessage());
            }
        } else {
            logger.error("传入参数值为空");
            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), SystemCode.ParameterValidError.getMessage());
        }
    }


    /**
     * @return
     */
    @GetMapping("/stop")
    @ApiOperation(value = "答题器停止服务接口", notes = "答题器停止服务接口，包括：停止签到、停止答题、断开操作等功能，无参输入，成功返回 code=0, 否则返回601错误码")
    public RestResponse<String> getStop() {
        logger.info("签到答题停止接口 getStop is begin");
        try {

            JVoteSdk.INSTANCE.Stop((short) BaseConstant.ALL_VOTE, (short) BaseConstant.ALL_VOTE);
            return RestResponse.ok();

        } catch (Exception e) {
            logger.error("签到答题停止接口执行失败：" + e.getMessage());
            return RestResponse.fail(SystemCode.VoteSDKConnection.getCode(), e.getMessage());
        }
    }



//    public static void main(String args[]){
//        VoteVM voteVM = new VoteVM();
//        voteVM.setExamId(2);
//        voteVM.setClassId(5);
//        QuestionEditRequestVM questionEditRequestVM = new QuestionEditRequestVM();
//        questionEditRequestVM.setId(12);
//        voteVM.setQuestionEditRequestVM(questionEditRequestVM);
//
//        System.out.println(JSONObject.toJSONString(voteVM));
//    }

}
